package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.ICartService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.ProductSku;
import com.spzx.product.api.domain.vo.SkuPrice;
import io.jsonwebtoken.lang.Assert;
import jakarta.annotation.Resource;
import org.apache.catalina.realm.SecretKeyCredentialHandler;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ICartServiceImpl implements ICartService {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    RemoteProductService remoteProductService;

    private String getCarKey(Long userId){
        return "user:cart:" +userId;
    }
    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        CartInfo cartInfo = new CartInfo();
        Long userId = SecurityContextHolder.getUserId();
        String carKey = getCarKey(userId);
        cartInfo =(CartInfo) redisTemplate.opsForHash().get(carKey, skuId + "");
        if (cartInfo == null) {
            ProductSku productSku = remoteProductService.getProductSku(skuId, SecurityConstants.INNER).getData();
            SkuPrice skuPrice = remoteProductService.getSkuPrice(skuId, SecurityConstants.INNER).getData();
            // 存入redis数据库
            cartInfo = new CartInfo();
            cartInfo.setUserId(userId);
            cartInfo.setSkuNum(skuNum > 99 ? 99 : skuNum);
            cartInfo.setUpdateTime(new Date());
            cartInfo.setCreateTime(new Date());
            cartInfo.setSkuId(skuId);
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setThumbImg(productSku.getThumbImg());
            Assert.isTrue(productSku.getSalePrice().compareTo(skuPrice.getSalePrice())==0, "价格变动");
            cartInfo.setCartPrice(skuPrice.getSalePrice());
            cartInfo.setSkuPrice(skuPrice.getSalePrice());
        }else {
            cartInfo.setSkuNum(cartInfo.getSkuNum()+skuNum);
        }
        redisTemplate.opsForHash().put(carKey, skuId+"", cartInfo);
    }

    @Override
    public List<CartInfo> getCarList() {
        Long userId = SecurityContextHolder.getUserId();
        String carKey = getCarKey(userId);
        List<CartInfo> cartInfoList =(List<CartInfo>) redisTemplate.boundHashOps(carKey).values();
        List<Long> skuIds = cartInfoList.stream().map(cartInfo -> {
            return cartInfo.getSkuId();
        }).collect(Collectors.toList());
//        R<List<SkuPrice>> skuPriceListR= remoteProductService.getSkuPriceList(skuIds,SecurityConstants.INNER);
        R<List<SkuPrice>> skuPriceListR = remoteProductService.getSkuPriceList(skuIds, SecurityConstants.INNER);
        List<SkuPrice>  skuPrices = skuPriceListR.getData();
        HashMap<Long, BigDecimal> hashMap = new HashMap<>();
        Map<Long, BigDecimal> collect = skuPrices.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        for (CartInfo cartInfo:cartInfoList) {
            cartInfo.setCartPrice(hashMap.get(cartInfo.getSkuId()));
        }
        return null;
    }

    @Override
    public void delectCart(Long skuId) {
        Long userId = SecurityContextHolder.getUserId();
        String carKey = getCarKey(userId);
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(carKey);
        hashOps.delete(skuId.toString());
    }

    @Override
    public void checkCart(Long skuId, Integer isChecked) {
        Long userId = SecurityContextHolder.getUserId();
        String carKey = getCarKey(userId);
        BoundHashOperations<String, String, CartInfo> hashOps = redisTemplate.boundHashOps(carKey);
        if (hashOps.hasKey(skuId.toString())) {
            CartInfo cartInfoUp = hashOps.get(skuId.toString());
            cartInfoUp.setIsChecked(isChecked);
            hashOps.put(skuId.toString(), cartInfoUp);
        }
    }

    @Override
    public void allCheckCart(Integer isChecked) {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        String carKey = getCarKey(userId);
        BoundHashOperations<String, String, CartInfo> hashOperations = redisTemplate.boundHashOps(carKey);
        List<CartInfo> cartInfoList = hashOperations.values();
        cartInfoList.forEach(item -> {
            CartInfo cartInfoUpd = hashOperations.get(item.getSkuId().toString());
            cartInfoUpd.setIsChecked(isChecked);

            // 更新缓存
            hashOperations.put(item.getSkuId().toString(), cartInfoUpd);
        });
    }

    @Override
    public void clearCart() {
        // 获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = getCarKey(userId);
        //获取缓存对象
        redisTemplate.delete(cartKey);
    }

    @Override
    public List<CartInfo> checkCartList(Long skuId, Integer checkStatus) {
        String carKey = getCarKey(skuId);
        List<CartInfo> cartInfoList = (List<CartInfo>) redisTemplate.boundHashOps(carKey);
        List<CartInfo> collect = cartInfoList.stream().filter(cartInfo -> {
            return cartInfo.getIsChecked() == 1;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void updateCartPrice(Long userId) {
        Long id = SecurityContextHolder.getUserId();
        String carKey = getCarKey(id);
        List<CartInfo> cartInfoList = (List<CartInfo>) redisTemplate.boundHashOps(carKey).values();
        for (CartInfo cartInfo:cartInfoList) {
            Long skuId = cartInfo.getSkuId();
            ProductSku productSku = remoteProductService.getProductSku(skuId, SecurityConstants.INNER).getData();
            BigDecimal salePrice = productSku.getSalePrice();
            cartInfo.setCartPrice(salePrice);
            cartInfo.setSkuPrice(salePrice);
            redisTemplate.boundHashOps(carKey).put(cartInfo.getSkuId().toString(), cartInfo);
        }

    }

    @Override
    public void deleteCartCheckedList(Long userId) {
        Long userId1 = SecurityContextHolder.getUserId();
        String carKey = getCarKey(userId);
        List<CartInfo> cartInfoList = (List<CartInfo>) redisTemplate.boundHashOps(carKey);
        for (CartInfo cartInfo: cartInfoList) {
            Integer isChecked = cartInfo.getIsChecked();
            if (isChecked == 1) {
                redisTemplate.boundHashOps(carKey).delete(cartInfo.getSkuId()+"");
            }
        }
    }
}
